package com.itheima.controller;


import com.itheima.config.AliOssUtil;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;
@Api(tags = "FileController-文件上传管理")
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @Autowired
    private  AliOssUtil ossUtil;


    //图片上传
    @ApiOperation(value = "文件上传",notes = "文件上传")
    @ApiParam(name = "imgFile",value = "文件",required = true,type = "File")
    @PostMapping("/upload")
    public Result upload(@RequestPart @RequestParam("imgFile") MultipartFile imgFile){
        String originalFilename = imgFile.getOriginalFilename();//原始文件名
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String fileName = UUID.randomUUID().toString() + suffix;
        //将图片保存到OSS
        try{
            //QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            String filePath = ossUtil.upload(imgFile.getBytes(), fileName);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,filePath);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
        }
    }
}
